# random templates here; i.e., same % missing as each template but "?" distributed randomly
library(tidyverse)
library(phangorn)
#Glires
matrix<-read.nexus.data("sampleMatrix.nex") #note read.nexus.data cannot read multistates; see ?read.nexus.data
tnames<-attr(matrix,"names") #put taxon names into vector "tnames"
dfmatrix<-data.frame(matrix)
rtbatch<-"randGliresTemplatesBatch.txt"
rtmeta<-"rtmetadata.csv"

#write initial TNT commands to batch file
write(paste("mxram 500","\n", #adjust mxram for your dataset, with nstates <8 TNT will tell you how much RAM is needed (but doesn't give accurate values when nstates>8). For huge datasets this may need to be over 1500; I think on 32bit TNT (no 64bit available, unfortunately) the max might be around here...
            "randTglires.log","\n", #so TNT writes details of search to a logfile which you'll want to rename 
            "taxname=;","\n",sep = ""),file = rtbatch,append = T) #to ensure taxnames are readable (otherwise they're numbers)
			
write(paste("subject","template","%missing",sep = ","),file = rtmeta,append = T)

#add subject/template taxon data here
starttemplate=62 #fossils
endtemplate=124
startsubject=2 #subjects
endsubject=61
#add morph partition data here
morphtotal = length(dfmatrix[,1])
#loop writes both TNT script for Ntemplate x Nsubject analyses and csv file with metadata for each template
for (i in starttemplate:endtemplate) {
  for (x in startsubject:endsubject) {
    template<-tnames[i]
    subject<-tnames[x]
    chars<-dfmatrix[,i]
    string<-paste(chars,collapse = "")
    qmarks<-str_locate_all(string,"\\?")
    qm<-data.frame(qmarks[1]) #convert into df & read only non-redundant start positions in qs$start
    propM<-length(qm$start)/morphtotal
    rand<-sample(0:(morphtotal-1),morphtotal*propM,replace = F)
    write(paste("proc sampleComb.tnt;","\n",
				"taxcode -{fossils};","\n",
                "xread=[",sep = ""),file = rtbatch,append = T)
    write(paste(rand, collapse=" ",sep = " "),file = rtbatch,append = T)
    write(paste(" 219.16137] ", x-1," ?;", "\n", #x-1 gives TNT number (starting from 0) corresponding to relevant subject taxon
                "mult=rep 100 hold 10; bbreak=tbr; nelsen *;","\n",
                "export - rt",subject,"_",template,".out; tchoose -.;","\n", sep = ""),file = rtbatch, append = T)
    write(paste(subject,template,propM*100,sep = ","),file = rtmeta,append = T)
  }
}
write(paste("mult:;","\n","log/;",sep=""),file=rtbatch,append=T)
